import PathFindEditor from "./PathFindEditor";
import ResKeeper from "../framework/res/ResKeeper";

/**
 * 简单地图编辑器
 */
const {ccclass, property} = cc._decorator;

@ccclass
export default class EditorMap extends ResKeeper {
    
    @property(cc.EditBox)
    edit:cc.EditBox = null;
    
    @property(cc.Label)
    modeBtnText:cc.Label = null;

    @property(PathFindEditor)
    pathFindEdit: PathFindEditor = null
 
    
    fileName:string = "newMap";
    

    onLoad(){
        this.pathFindEdit.setEdit(this);
    }


    /**
     * 保存地图数据
     */
    onSaveMapJson(){
        let mapInfo = this.pathFindEdit.getMapData();
        var blob = new Blob([JSON.stringify(mapInfo)], {type: "text/plain;charset=utf-8"});
        this.saveForBrowser(blob, `${this.fileName}.json`);
    } 
  
    //保存数据
   private saveForBrowser(textToWrite, fileNameToSaveAs) {
        if (cc.sys.isBrowser) { 
            let textFileAsBlob = new Blob([textToWrite], {type:'application/json'});
            let downloadLink = document.createElement("a");
            downloadLink.download = fileNameToSaveAs;
            downloadLink.innerHTML = "Download File";
            if (window.webkitURL != null)
            { 
                //@ts-ignore
                downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
            }
            else
            { 
                //@ts-ignore
                downloadLink.href = window.URL.createObjectURL(textFileAsBlob); 
                downloadLink.style.display = "none";
                document.body.appendChild(downloadLink);
            }
            downloadLink.click();
        }
    }


   async onLoadMap(){
        let str = this.edit.string;
        if(!str){
            return;
        }
        this.fileName = str;
        let data:cc.Asset = await this.loadResAsync("map/map",cc.JsonAsset)
        let json:MapData = (data as cc.JsonAsset).json;
        this.pathFindEdit.initData(json);  
    }


}
